<?php
namespace houdun\model;
use PDO;
use Exception;
class Base{
    private static $pdo;
    private $table;//操作的数据表
    private $where = '';//where条件
    private $field = '*';//指定列数据
    private $order = '';//排序
    public function __construct ($class) {
        $this->table = strtolower (explode ('\\',$class)[2]);
        $this->connect();
    }

    /**
     * 删除
     * @return bool|int
     */
    public function delete(){
        if(!$this->where) return false;
        $sql = "delete from {$this->table}{$this->where}";
        return $this->e ($sql);
    }

    /**
     * 更新数据
     * @param $data
     *
     * @return bool|int
     */
    public function update($data){
        //没有where条件不进行更新
        if(!$this->where) return false;
        $fields = '';
        foreach ($data as $k=>$v){
            $fields .= $k . '=' . (is_int ($v)?$v:"'$v'") . ',';
        }
        $fields = rtrim ($fields,',');
        //p($fields);die;
        $sql = "update {$this->table} set {$fields}{$this->where}";
        //p($sql);die;
        return $this->e ($sql);
    }

    /**
     * 写入数据
     * @param $data
     *
     * @return int
     */
    public function insert($data){
        //p($data);
        //sname,age,sex
        //'后盾',18,'男'
        $fields = '';
        $values = '';
        foreach($data as $k=>$v){
            $fields .= $k . ',';
            $values .= (is_int ($v)?$v:"'$v'") . ',';
        }
        //将字符串最右侧,去掉
        $fields = rtrim ($fields,',');
        $values = rtrim ($values,',');
        //p($values);die;
        $sql = "insert into {$this->table} ({$fields}) values ({$values})";
        //p($sql);die;
        return $this->e ($sql);
    }

    /**
     * where条件
     * @param $where
     *
     * @return $this
     */
    public function where($where){
        //p($where);//sex='男'
        $this->where = ' where '.$where;
        return $this;
    }

    /**
     * 获取指定列字段
     * @param $field
     *
     * @return $this
     */
    public function field($field){
        $this->field = $field;
        return $this;
    }

    /**
     * 排序
     * @param $order
     *
     * @return $this
     */
    public function orderBy($order){
        $this->order = ' order by ' . $order;
        return $this;
    }

    /**
     * 获得所有数据
     * @return array
     */
    public function getAll(){
        //p($this->where);
        $sql = "select {$this->field} from {$this->table}{$this->where}{$this->order}";
        //p($sql);die;
        return $this->q ($sql);
    }

    /**
     * 根据主键查找数据
     * @param $primary
     */
    public function find($primary){
        $pk = $this->getPk ();
        //p($pk);
        //p($this->table);die;
        //假设找学生表主键id=1一条数据
        $sql = "select * from {$this->table} where {$pk}={$primary}";

//        p($sql);
		return current ($this->q ($sql));

        //$res = $this->q ($sql);
        //p(current ($res));
    }

    /**
     * 获取数据表主键字段
     */
    private function getPk(){
        $sql = "desc {$this->table}";
        //p($sql);die;
        $res = $this->q ($sql);
        //p($res);die;
        foreach($res as $k=>$v){
            if($v['Key'] == 'PRI'){
                $pk = $v['Field'];
                break;
            }
        }
        return $pk;
    }

    /**
     * 连接数据库
     */
    private function connect(){
        //p(c('database.host'));
        if(is_null (self::$pdo)){
            try{
                //p(self::$pdo);
                $dsn = 'mysql:host='.c('database.host').';dbname='.c('database.dbname');
                $username = c('database.user');
                $password = c('database.password');
                self::$pdo = new PDO($dsn,$username,$password);
                //设置字符集
                self::$pdo->query ('set names utf8');
                //设置错误属性
                self::$pdo->setAttribute (PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            }catch (Exception $e){
                die($e->getMessage ());
            }
        }
    }

    /**
     * 执行有结果集的操作：select
     * @param $sql
     *
     * @return array
     */
    public function q($sql){
        //调用pdo query
        try{
            return self::$pdo->query ($sql)->fetchAll (PDO::FETCH_ASSOC);
        }catch (Exception $e){
            die($e->getMessage ());
        }
    }

    /**
     * 执行无结果集的操作insert、update、delete
     * @param $sql
     *
     * @return int
     */
    public function e($sql){
        try{
            return self::$pdo->exec  ($sql);
        }catch (Exception $e){
            die($e->getMessage ());
        }
    }
}
